#include "pch.h"

std::unique_ptr<FPSCounter> FPSCounter::sInstance (new FPSCounter());

FPSCounter::FPSCounter()
{
    frame = 0;
    cap = true;
    movingUp = true;
    shown = false;

    fpsCounter = NULL;
}

FPSCounter::~FPSCounter()
{
    //dtor
}

// Unused
void FPSCounter::clear_surface()
{

}

bool FPSCounter::init()
{
    fps.Start();
    update.Start();
    elapsed.Start();

    if (sInstance)
    {
        return true;
    }
    return false;
}

bool FPSCounter::delayFrame()
{
    frame++;
    int ticks = fps.getTicks();
    //If we want to cap the frame rate
    if( (cap == true) && (ticks < 1000 / FRAMES_PER_SECOND) )
    {
        //Sleep the remaining frame time
        SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - ticks );
    }
    fps.Start();

    return true;
}

bool FPSCounter::updateFPS()
{
    //If a second has passed since the message was last updated
    if(update.getTicks() > 1000)
    {
        // FPS Counter
        std::stringstream fpsText;
        fpsText << "FPS: " << frame / ( update.getTicks() / 1000 );
        fpsCounter = TTF_RenderText_Blended(GraphicsDevice::sInstance->getFont(), (fpsText.str()).c_str(), GraphicsDevice::sInstance->getTextColor());

        //Restart the update timer
        update.Start();
        movingUp = !movingUp;
        frame = 0;
    }

    return true;
}

void FPSCounter::toggleFps()
{
    shown = (!shown);
}
